package com.test.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import scala.util.Random;

public class ReadWriteLockDemo {

	private static Lock lock = new ReentrantLock();
	private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	private static Lock readLock = readWriteLock.readLock();
	private static Lock writeLock = readWriteLock.writeLock();
	private int value;

	public Object handleRead(Lock lock) throws InterruptedException {
		lock.lock();
		try {
			Thread.sleep(1000);
			System.out.println(value);
			return value;
		} finally {
			lock.unlock();
		}

	}

	public void handleWrite(Lock lock, int index) throws InterruptedException {
		lock.lock();
		try {
			Thread.sleep(1000);
			value = index;
			System.out.println(value);
		} finally {
			lock.unlock();
		}

	}

	public static void main(String[] args) {
		final ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
		Runnable readRunnable = new Runnable() {

			public void run() {
				try {
					//readWriteLockDemo.handleRead(readLock);
					readWriteLockDemo.handleRead(lock);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		};
		Runnable writeRunnable = new Runnable() {

			public void run() {
				try {
					//readWriteLockDemo.handleWrite(writeLock, new Random().nextInt());
					readWriteLockDemo.handleWrite(lock, new Random().nextInt());
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		};

		for (int i = 0; i < 18; i++) {
			new Thread(readRunnable).start();
		}

		for (int i = 0; i < 18; i++) {
			new Thread(writeRunnable).start();
		}
	}
}
